<script setup lang="ts">
import { computed, onMounted, ref } from 'vue';
import { useRouter } from 'vue-router';

import {
  BankOutlined,
  BookOutlined,
  CrownOutlined,
  DollarOutlined,
  FileTextOutlined,
  FireOutlined,
  SafetyCertificateOutlined,
  TrophyOutlined,
  UserOutlined,
} from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';
import dayjs from 'dayjs';

import MemberDistributionChart from '../../../components/charts/MemberDistributionChart.vue';
import TreasuryTrendChart from '../../../components/charts/TreasuryTrendChart.vue';
import WalletConnect from '../../../components/common/WalletConnect.vue';
import { governanceProposals } from '../../../mock/zhu-dynasty/governance';
import {
  historicalEvents,
  kingdoms,
  zhuMembers,
} from '../../../mock/zhu-dynasty/members';

const router = useRouter();
const mapRef = ref<HTMLDivElement>();
const showWelcome = ref(true);
const statsAnimated = ref(false);

// 统计数据
const stats = computed(() => ({
  totalMembers: zhuMembers.length,
  totalKingdoms: kingdoms.filter((k) => k.status === 'active').length,
  totalTreasury: kingdoms.reduce((sum, k) => sum + k.treasury, 0),
  sbtCount: zhuMembers.filter((m) => m.hasSBT).length,
  activeProposals: governanceProposals.filter((p) => p.status === 'voting')
    .length,
}));

// 当前皇帝
const currentEmperor = computed(
  () =>
    zhuMembers.find((m) => m.role === 'emperor' && !m.deathDate) ||
    zhuMembers[0],
);

// 最近事件
const recentEvents = computed(() => historicalEvents.slice(0, 5));

// 活跃藩国
const activeKingdoms = computed(() =>
  kingdoms.filter((k) => k.status === 'active').slice(0, 6),
);

// 最新提案
const recentProposals = computed(() => governanceProposals.slice(0, 3));

// 世代汇总
const generationSummary = computed(() => {
  const generations = new Map();
  zhuMembers.forEach((member) => {
    if (!generations.has(member.generation)) {
      generations.set(member.generation, []);
    }
    generations.get(member.generation).push(member);
  });

  return [...generations.entries()]
    .map(([generation, members]) => ({ generation, members }))
    .sort((a, b) => a.generation - b.generation)
    .slice(0, 4); // 只显示前4代
});

function getEventColor(importance: string) {
  const colors = {
    critical: 'red',
    major: 'blue',
    normal: 'gray',
  };
  return colors[importance] || 'gray';
}

function getEventIcon(type: string) {
  const icons = {
    political: BankOutlined,
    military: FireOutlined,
    cultural: BookOutlined,
    governance: CrownOutlined,
    ceremony: TrophyOutlined,
  };
  return icons[type] || BookOutlined;
}

function getKingdomColor(type: string) {
  return type === 'imperial' ? 'gold' : 'blue';
}

function formatDate(date: string) {
  return dayjs(date).format('YYYY年MM月DD日');
}

function formatMoney(amount: number) {
  return `${(amount / 10_000).toFixed(0)}万两`;
}

// 欢迎动画
onMounted(() => {
  // 显示欢迎消息
  const hour = new Date().getHours();
  const greeting = hour < 12 ? '早上好' : (hour < 18 ? '下午好' : '晚上好');
  message.success(`${greeting}！欢迎回到朱氏皇族管理系统 👑`);

  // 3秒后隐藏欢迎遮罩
  setTimeout(() => {
    showWelcome.value = false;
  }, 2000);

  // 触发数字动画
  setTimeout(() => {
    statsAnimated.value = true;
  }, 500);
});

function viewKingdom(kingdom: any) {
  router.push(`/zhu-family/kingdom?id=${kingdom.id}`);
}

function viewMember(member: any) {
  router.push(`/zhu-family/genealogy?member=${member.id}`);
}

function viewProposal(proposal: any) {
  router.push(`/zhu-family/governance?proposal=${proposal.id}`);
}
</script>

<template>
  <div class="zhu-dynasty-dashboard">
    <!-- 欢迎遮罩动画 -->
    <transition name="welcome-fade">
      <div v-if="showWelcome" class="welcome-overlay">
        <div class="welcome-content">
          <div class="welcome-icon">
            <CrownOutlined class="crown-spin" />
          </div>
          <h1 class="welcome-title">朱氏皇族</h1>
          <p class="welcome-subtitle">数字文明 · 世代传承</p>
          <div class="welcome-particles"></div>
        </div>
      </div>
    </transition>

    <!-- 朝代头部 -->
    <div class="dynasty-header">
      <div class="dynasty-seal">
        <div class="seal-placeholder">
          <CrownOutlined style="font-size: 64px; color: #daa520" />
        </div>
      </div>
      <div class="dynasty-info">
        <h1>大明王朝 · 朱氏皇族治理中台</h1>
        <p class="dynasty-motto">驱除鞑虏，恢复中华，立纲陈纪，救济斯民</p>
        <div class="dynasty-stats">
          <a-space :size="32">
            <a-statistic
              title="皇族成员"
              :value="stats.totalMembers"
              suffix="人"
            />
            <a-statistic
              title="藩国数量"
              :value="stats.totalKingdoms"
              suffix="个"
            />
            <a-statistic
              title="国库总额"
              :value="stats.totalTreasury / 10000"
              suffix="万两"
            />
            <div class="emperor-info">
              <div class="label">在位皇帝</div>
              <div class="value">{{ currentEmperor.title }}</div>
            </div>
          </a-space>
        </div>
      </div>
    </div>

    <!-- 钱包连接区域 -->
    <a-card title="🔗 区块链钱包连接" style="margin-top: 16px;">
      <WalletConnect />
    </a-card>

    <!-- 核心数据卡片 -->
    <a-row :gutter="16" style="margin-top: 16px">
      <a-col :span="6">
        <a-card class="stat-card">
          <a-statistic title="皇族成员" :value="stats.totalMembers" suffix="人">
            <template #prefix>
              <UserOutlined style="color: #1890ff" />
            </template>
          </a-statistic>
        </a-card>
      </a-col>
      <a-col :span="6">
        <a-card class="stat-card">
          <a-statistic
            title="国库总额"
            :value="stats.totalTreasury / 10000"
            suffix="万两"
          >
            <template #prefix>
              <DollarOutlined style="color: #faad14" />
            </template>
          </a-statistic>
        </a-card>
      </a-col>
      <a-col :span="6">
        <a-card class="stat-card">
          <a-statistic title="链上 SBT" :value="stats.sbtCount" suffix="枚">
            <template #prefix>
              <SafetyCertificateOutlined style="color: #52c41a" />
            </template>
          </a-statistic>
        </a-card>
      </a-col>
      <a-col :span="6">
        <a-card class="stat-card">
          <a-statistic
            title="进行中提案"
            :value="stats.activeProposals"
            suffix="项"
          >
            <template #prefix>
              <FileTextOutlined style="color: #722ed1" />
            </template>
          </a-statistic>
        </a-card>
      </a-col>
    </a-row>

    <!-- 藩国地图 -->
    <a-card
      title="🗺️ 大明疆域 · 藩国分布"
      class="map-card"
      style="margin-top: 16px"
    >
      <div class="kingdom-map">
        <div class="map-container" ref="mapRef">
          <div
            v-for="kingdom in kingdoms"
            :key="kingdom.id"
            class="kingdom-marker"
          >
            <a-tooltip :title="kingdom.description">
              <div class="marker" @click="viewKingdom(kingdom)">
                <span>{{ kingdom.name }}</span>
              </div>
            </a-tooltip>
          </div>
        </div>
      </div>
    </a-card>

    <!-- 主要内容区 -->
    <a-row :gutter="16" style="margin-top: 16px">
      <!-- 皇室动态 -->
      <a-col :span="12">
        <a-card title="📜 皇室动态">
          <a-timeline>
            <a-timeline-item
              v-for="event in recentEvents"
              :key="event.id"
              :color="getEventColor(event.importance)"
            >
              <template #dot>
                <component
                  :is="getEventIcon(event.type)"
                  style="font-size: 16px"
                />
              </template>
              <div class="event-item">
                <h4>{{ event.title }}</h4>
                <p>{{ event.description }}</p>
                <span class="event-meta">
                  {{ formatDate(event.date) }} · {{ event.location }}
                </span>
              </div>
            </a-timeline-item>
          </a-timeline>
          <a-button
            type="link"
            block
            @click="router.push('/zhu-family/archive')"
          >
            查看更多历史事件 →
          </a-button>
        </a-card>
      </a-col>

      <!-- 藩国概览 -->
      <a-col :span="12">
        <a-card title="🏯 藩国概览">
          <a-list :data-source="activeKingdoms" size="small">
            <template #renderItem="{ item }">
              <a-list-item>
                <template #actions>
                  <a @click="viewKingdom(item)">查看</a>
                </template>
                <a-list-item-meta>
                  <template #title>
                    <a-space>
                      <span>{{ item.name }}</span>
                      <a-tag :color="getKingdomColor(item.type)">
                        {{ item.type === 'imperial' ? '帝都' : '藩国' }}
                      </a-tag>
                    </a-space>
                  </template>
                  <template #description>
                    <div class="kingdom-info">
                      <span>📍 {{ item.capital }}</span>
                      <span>👑 {{ item.currentRuler }}</span>
                      <span>💰 {{ formatMoney(item.treasury) }}</span>
                    </div>
                  </template>
                </a-list-item-meta>
              </a-list-item>
            </template>
          </a-list>
          <a-button
            type="link"
            block
            @click="router.push('/zhu-family/kingdom')"
          >
            查看所有藩国 →
          </a-button>
        </a-card>
      </a-col>
    </a-row>

    <!-- 皇族世系快览 -->
    <a-card title="🌳 皇族世系快览" style="margin-top: 16px">
      <div class="quick-genealogy">
        <a-space direction="vertical" size="large" style="width: 100%">
          <div
            v-for="gen in generationSummary"
            :key="gen.generation"
            class="generation-row"
          >
            <div class="generation-title">
              <a-tag color="gold">第 {{ gen.generation }} 代</a-tag>
              <span>{{ gen.members.length }} 人</span>
            </div>
            <a-space wrap>
              <a-tooltip
                v-for="member in gen.members"
                :key="member.id"
                :title="`${member.title} ${member.name}`"
              >
                <a-badge
                  :count="member.role === 'emperor' ? '帝' : ''"
                  :number-style="{ backgroundColor: '#faad14' }"
                >
                  <a-avatar
                    :src="member.avatar"
                    :size="50"
                    @click="viewMember(member)"
                    style="cursor: pointer"
                  />
                </a-badge>
              </a-tooltip>
            </a-space>
          </div>
        </a-space>
      </div>

      <a-button
        type="primary"
        block
        style="margin-top: 16px"
        @click="router.push('/zhu-family/genealogy')"
      >
        查看完整族谱
      </a-button>
    </a-card>

    <!-- 数据可视化 -->
    <a-row :gutter="16" style="margin-top: 16px">
      <a-col :span="12">
        <a-card title="📈 国库收支趋势">
          <TreasuryTrendChart />
        </a-card>
      </a-col>
      <a-col :span="12">
        <a-card title="👥 成员世代分布">
          <MemberDistributionChart />
        </a-card>
      </a-col>
    </a-row>

    <!-- 治理提案 -->
    <a-card title="⚖️ 最新提案" style="margin-top: 16px">
      <a-list :data-source="recentProposals" size="small">
        <template #renderItem="{ item }">
          <a-list-item>
            <template #actions>
              <a @click="viewProposal(item)">查看详情</a>
            </template>
            <a-list-item-meta
              :title="item.title"
              :description="item.description"
            >
              <template #avatar>
                <a-avatar style="background-color: #1890ff">
                  {{
                    item.type === 'law'
                      ? '律'
                      : item.type === 'finance'
                        ? '财'
                        : '军'
                  }}
                </a-avatar>
              </template>
            </a-list-item-meta>
            <div class="proposal-status">
              <a-progress
                :percent="
                  Math.round((item.votesFor / item.votesRequired) * 100)
                "
                :status="item.status === 'passed' ? 'success' : 'active'"
                size="small"
              />
              <span class="vote-count">{{ item.votesFor }}/{{ item.votesRequired }}</span>
            </div>
          </a-list-item>
        </template>
      </a-list>
      <a-button
        type="link"
        block
        @click="router.push('/zhu-family/governance')"
      >
        查看所有提案 →
      </a-button>
    </a-card>
  </div>
</template>

<style scoped lang="scss">
.zhu-dynasty-dashboard {
  // 欢迎动画关键帧
  @keyframes float {
    0%,
    100% {
      transform: translateY(0);
    }

    50% {
      transform: translateY(-20px);
    }
  }

  @keyframes pulse {
    0%,
    100% {
      filter: drop-shadow(0 0 30px rgb(255 215 0 / 80%));
      transform: scale(1);
    }

    50% {
      filter: drop-shadow(0 0 50px rgb(255 215 0 / 100%));
      transform: scale(1.1);
    }
  }

  @keyframes fadeInUp {
    from {
      opacity: 0;
      transform: translateY(30px);
    }

    to {
      opacity: 1;
      transform: translateY(0);
    }
  }

  @keyframes countUp {
    from {
      opacity: 0;
      transform: scale(0.5);
    }

    to {
      opacity: 1;
      transform: scale(1);
    }
  }

  .dynasty-header {
    display: flex;
    gap: 24px;
    align-items: center;
    padding: 32px;
    margin-bottom: 16px;
    color: white;
    background: linear-gradient(135deg, #b8860b 0%, #daa520 100%);
    border-radius: 12px;

    .dynasty-seal {
      .seal-placeholder {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 120px;
        height: 120px;
        background: rgb(255 255 255 / 10%);
        border-radius: 50%;
      }
    }

    .dynasty-info {
      flex: 1;

      h1 {
        margin: 0 0 8px;
        font-size: 32px;
        color: white;
        text-shadow: 2px 2px 4px rgb(0 0 0 / 30%);
      }

      .dynasty-motto {
        margin: 0 0 20px;
        font-size: 14px;
        opacity: 0.9;
      }

      .dynasty-stats {
        :deep(.ant-statistic-title) {
          color: rgb(255 255 255 / 85%);
        }

        :deep(.ant-statistic-content) {
          color: white;
        }

        .emperor-info {
          .label {
            margin-bottom: 4px;
            font-size: 14px;
            color: rgb(255 255 255 / 85%);
          }

          .value {
            font-size: 24px;
            font-weight: bold;
            color: white;
          }
        }
      }
    }
  }

  .stat-card {
    text-align: center;
  }

  .map-card {
    .kingdom-map {
      .map-container {
        position: relative;
        display: flex;
        flex-wrap: wrap;
        gap: 16px;
        align-items: center;
        justify-content: center;
        width: 100%;
        height: 300px;
        padding: 24px;
        background: linear-gradient(180deg, #e3f2fd 0%, #f5f5dc 100%);
        border-radius: 8px;

        .kingdom-marker {
          .marker {
            padding: 8px 16px;
            cursor: pointer;
            background: white;
            border: 2px solid #1890ff;
            border-radius: 8px;
            transition: all 0.3s;

            &:hover {
              color: white;
              background: #1890ff;
              box-shadow: 0 4px 12px rgb(24 144 255 / 30%);
              transform: translateY(-2px);
            }
          }
        }
      }
    }
  }

  .event-item {
    h4 {
      margin: 0 0 8px;
      font-size: 14px;
    }

    p {
      margin: 0 0 8px;
      font-size: 13px;
      color: #666;
    }

    .event-meta {
      font-size: 12px;
      color: #999;
    }
  }

  .kingdom-info {
    display: flex;
    gap: 16px;
    font-size: 12px;
  }

  .quick-genealogy {
    .generation-row {
      padding: 16px;
      background: #fafafa;
      border-radius: 8px;

      .generation-title {
        display: flex;
        gap: 12px;
        align-items: center;
        margin-bottom: 12px;
        font-weight: bold;
      }
    }
  }

  .proposal-status {
    display: flex;
    flex-direction: column;
    gap: 4px;
    align-items: flex-end;

    .vote-count {
      font-size: 12px;
      color: #666;
    }
  }

  // 欢迎遮罩动画
  .welcome-overlay {
    position: fixed;
    inset: 0;
    z-index: 9999;
    display: flex;
    align-items: center;
    justify-content: center;
    background: linear-gradient(135deg, #1a1a2e 0%, #16213e 50%, #0f3460 100%);

    .welcome-content {
      color: white;
      text-align: center;

      .welcome-icon {
        margin-bottom: 24px;
        animation: float 3s ease-in-out infinite;

        .crown-spin {
          font-size: 120px;
          color: #ffd700;
          filter: drop-shadow(0 0 30px rgb(255 215 0 / 80%));
          animation: pulse 2s ease-in-out infinite;
        }
      }

      .welcome-title {
        margin-bottom: 16px;
        font-size: 48px;
        font-weight: bold;
        color: #ffd700;
        text-shadow: 0 0 20px rgb(255 215 0 / 50%);
        animation: fadeInUp 1s ease-out;
      }

      .welcome-subtitle {
        font-size: 20px;
        color: #e0e0e0;
        letter-spacing: 8px;
        animation: fadeInUp 1s ease-out 0.3s both;
      }
    }
  }

  // 过渡效果
  .welcome-fade-enter-active,
  .welcome-fade-leave-active {
    transition: all 0.8s ease;
  }

  .welcome-fade-enter-from {
    opacity: 0;
  }

  .welcome-fade-leave-to {
    opacity: 0;
    transform: scale(1.1);
  }

  // 统计卡片悬浮效果
  .stat-card {
    cursor: pointer;
    transition: all 0.3s ease;

    &:hover {
      box-shadow: 0 12px 24px rgb(0 0 0 / 15%);
      transform: translateY(-8px);
    }
  }

  // 数字滚动动画
  :deep(.ant-statistic-content-value) {
    animation: countUp 1.5s ease-out;
  }
}
</style>
